import requests
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.contrib.auth.models import User
from django.conf import settings 
# from .models import Credential, CredentialImportLog
from apps.credentials.models import Credential, CredentialImportLog


@csrf_exempt
def chat_api(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_message = data.get('message', '')
            
            print(f"收到消息: {user_message}")  # 调试日志
            
            # 从settings获取配置
            api_key = settings.DEEPSEEK_CONFIG['api_key']
            base_url = settings.DEEPSEEK_CONFIG['base_url']
            
            headers = {
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            }
            
            payload = {
                "model": "deepseek-chat",
                "messages": [
                    {
                        "role": "user", 
                        "content": user_message
                    }
                ],
                "stream": False
            }
            
            print(f"发送请求到: {base_url}/chat/completions")  # 调试日志
            
            response = requests.post(
                f"{base_url}/chat/completions",
                headers=headers,
                json=payload,
                timeout=30
            )
            
            print(f"API响应状态码: {response.status_code}")  # 调试日志
            
            if response.status_code == 200:
                result = response.json()
                print(f"API响应内容: {result}")  # 调试日志
                
                ai_response = result['choices'][0]['message']['content']
                
                return JsonResponse({
                    'success': True,
                    'response': ai_response
                })
            else:
                error_detail = response.text
                print(f"API错误详情: {error_detail}")  # 调试日志
                return JsonResponse({
                    'success': False,
                    'error': f'API调用失败: {response.status_code} - {error_detail}'
                })
                
        except Exception as e:
            print(f"异常错误: {str(e)}")  # 调试日志
            return JsonResponse({
                'success': False,
                'error': f'请求异常: {str(e)}'
            })
    
    return JsonResponse({'error': '仅支持POST请求'})


@csrf_exempt
@require_POST
def save_credentials(request):
    """保存解析的凭证数据"""
    try:
        data = json.loads(request.body)
        credentials_data = data.get('credentials', [])
        file_info = data.get('file_info', {})
        
        print(f"开始保存凭证数据，共 {len(credentials_data)} 条记录")  # 调试日志
        
        if not credentials_data:
            return JsonResponse({'success': False, 'error': '没有可保存的凭证数据'})
        
        # 使用默认用户（如果没有认证系统）
        try:
            user = User.objects.first()
            if not user:
                user = User.objects.filter(is_superuser=True).first()
            print(f"使用用户: {user.username}")  # 调试日志
        except Exception as e:
            print(f"用户获取失败: {str(e)}")  # 调试日志
            return JsonResponse({'success': False, 'error': '用户配置错误'})
        
        saved_count = 0
        error_count = 0
        saved_records = []
        
        for i, cred_data in enumerate(credentials_data):
            try:
                credential = Credential(
                    location=cred_data.get('location', ''),
                    device_name=cred_data.get('device_name', ''),
                    username=cred_data.get('username', ''),
                    password=cred_data.get('password', ''),
                    url=cred_data.get('url', ''),
                    protocol=cred_data.get('protocol', ''),
                    status=cred_data.get('status', 'normal'),
                    notes=cred_data.get('notes', ''),
                    source_file=file_info.get('file_name', ''),
                    created_by=user
                )
                credential.save()
                saved_count += 1
                saved_records.append({
                    'location': cred_data.get('location'),
                    'device_name': cred_data.get('device_name')
                })
                print(f"保存第 {i+1} 条记录成功")  # 调试日志
            except Exception as e:
                error_count += 1
                print(f"保存第 {i+1} 条记录失败: {str(e)}")  # 调试日志
                continue
        
        # 记录导入日志
        import_log = CredentialImportLog.objects.create(
            file_name=file_info.get('file_name', ''),
            file_path=file_info.get('file_path', ''),
            total_count=len(credentials_data),
            success_count=saved_count,
            import_by=user,
            parse_result={
                'saved_records': saved_records,
                'error_count': error_count
            }
        )
        
        print(f"保存完成: 成功 {saved_count} 条，失败 {error_count} 条")  # 调试日志
        
        return JsonResponse({
            'success': True,
            'message': f'成功保存 {saved_count} 条凭证记录',
            'saved_count': saved_count,
            'error_count': error_count,
            'total_count': len(credentials_data),
            'log_id': import_log.id
        })
        
    except Exception as e:
        print(f"保存凭证异常: {str(e)}")  # 调试日志
        return JsonResponse({'success': False, 'error': f'保存失败: {str(e)}'})